package net.wicp.tams.common.os.pool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.beans.Host;

/***
 * 与SSHPoolByKey不同的是，它可以防连接泄漏，但开发者还是需要手动关闭连接，防止出全部连接在同一时候关闭时的闪动现象
 * 
 * @author 偏锋书生
 *
 *         2018年8月22日
 */
public class SSHPoolByMap {
	private Map<Host, SSHPool> allPool = new HashMap<>();
	private final List<Host> hostList = new ArrayList<>();
	private final GenericObjectPoolConfig<SSHConnection> poolConfig;

	public SSHPoolByMap(List<Host> conf) {
		this(conf, new GenericObjectPoolConfig<SSHConnection>());
	}

	public SSHPoolByMap(List<Host> conf, GenericObjectPoolConfig<SSHConnection> poolConfig) {
		this.poolConfig = poolConfig;
		if (conf != null) {
			hostList.addAll(conf);
		}
	}

	public void addHost(Host key) {
		this.hostList.add(key);
	}

	public SSHConnection borrowObject(Host key) throws Exception {
		if (!allPool.containsKey(key)) {
			synchronized (SSHFactoryByKey.class) {
				if (!allPool.containsKey(key)) {
					int indexOf = hostList.indexOf(key);
					if (indexOf < 0) {
						indexOf = hostList.size();
						hostList.add(key);
					}
					Host host = hostList.get(indexOf);// 可能传入只设置了ip和端口的key过来
					SSHPool fat = new SSHPool(host.getHostIp(), host.getPort(),
							StringUtil.hasNull(host.getUserName(), Conf.get("common.os.ssh.username")),
							StringUtil.hasNull(host.getPassword(), Conf.get("common.os.ssh.pwd")), poolConfig);
					allPool.put(host, fat);
				}
			}
		}
		SSHConnection conn = allPool.get(key).borrowObject();
		return conn;
	}

	public void returnObject(Host key, SSHConnection conn) throws Exception {
		if (allPool.get(key) != null) {
			allPool.get(key).returnObject(conn);
		}
	}
}
